package Thread2;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 解决线程安全的方式三：Lock锁----jdk5.0新增
 *
 *
 */
public class Demo2 {
    public static void main(String[] args) {
        window9 w1 = new window9();
        Thread t1 = new Thread(w1);
        Thread t2 = new Thread(w1);
        Thread t3 = new Thread(w1);
        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");
        t1.start();
        t2.start();
        t3.start();
    }

}

class window9 implements Runnable {
    private int ticket = 100;

    //实例化，创建一个锁对象：lock
    private ReentrantLock lock = new ReentrantLock();


    @Override
    public void run() {
        while (true) {
            try {
                //调用当前对象的lock（）方法
                lock.lock();
                if (ticket > 0) {
//                    try {
//                        Thread.sleep(100);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
                    System.out.println(Thread.currentThread().getName() + "卖了票号为" + ticket);
                    ticket--;
                } else {
                    break;
                }
            } finally {
                lock.unlock();//释放锁
            }

        }

    }
}
